<template>
  <el-form
    v-show="getShow"
    ref="formLogin"
    :model="loginData.loginForm"
    :rules="LoginRules"
    label-position="top"
    label-width="120px"
    size="large"
    v-if="!isForget"
    class="login-form p-42px h-auto m-auto rounded-1xl bg-white w-30rem shadow-login-win <sm:(p-35px px-25px w-18.75rem shadow-login-mobile)"
  >
    <el-row>
      <el-col :span="24" style="padding-left: 10px; padding-right: 10px">
        <el-form-item>
          <LoginFormTitle style="width: 100%" />
        </el-form-item>
      </el-col>
      <!-- <el-col :span="24" style="padding-left: 10px; padding-right: 10px">
        <el-form-item v-if="loginData.tenantEnable === 'true'" prop="tenantName">
          <el-input
            v-model="loginData.loginForm.tenantName"
            :placeholder="t('login.tenantNamePlaceholder')"
            :prefix-icon="iconHouse"
            type="primary"
            link
          />
        </el-form-item>
      </el-col> -->
      <el-col :span="24" style="padding-left: 10px; padding-right: 10px" class="<sm:(h-4rem)">
        <el-form-item prop="username">
          <el-input
            v-model.trim="loginData.loginForm.username"
            :placeholder="t('login.usernamePlaceholder')"
            :prefix-icon="iconAvatar"
            class="w-20.875rem h-3rem loginInput <sm:h-2.25rem"
          />
        </el-form-item>
      </el-col>
      <el-col :span="24" style="padding-left: 10px; padding-right: 10px" class="<sm:(h-4rem)">
        <el-form-item prop="password">
          <el-input
            v-model.trim="loginData.loginForm.password"
            :placeholder="t('login.passwordPlaceholder')"
            :prefix-icon="iconLock"
            show-password
            type="password"
            @keyup.enter="getCode()"
            class="w-20.875rem h-3rem loginInput <sm:h-2.25rem"
          />
        </el-form-item>
      </el-col>
      <el-col :span="24" class="px-10px -mt-13px mb-21px <sm:(-mt-21px mb-0)">
        <el-form-item class="<sm:(!mb-0)">
          <el-row justify="space-between" style="width: 100%">
            <el-col :span="6">
              <el-checkbox v-model="loginData.loginForm.rememberMe">
                {{ t('login.remember') }}
              </el-checkbox>
            </el-col>
            <el-col :offset="6" :span="12">
              <el-link style="float: right" type="primary" :underline="false" @click="toForgetForm">
                {{ t('login.forgetPassword') }}
              </el-link>
            </el-col>
          </el-row>
        </el-form-item>
      </el-col>
      <el-col :span="24" style="padding-left: 10px; padding-right: 10px; margin-bottom: -22px">
        <el-form-item>
          <XButton
            :loading="loginLoading"
            :title="t('login.login')"
            class="w-[100%]"
            type="primary"
            @click="getCode()"
          />
        </el-form-item>
      </el-col>
      <Verify
        ref="verify"
        :captchaType="captchaType"
        :imgSize="dynamicImgSize"
        mode="pop"
        @success="handleLogin"
      />  
      <!--<el-col :span="24" style="padding-left: 10px; padding-right: 10px">
        <el-form-item>
          <el-row :gutter="5" justify="space-between" style="width: 100%">
            <el-col :span="8">
              <XButton
                :title="t('login.btnMobile')"
                class="w-[100%]"
                @click="setLoginState(LoginStateEnum.MOBILE)"
              />
            </el-col>
            <el-col :span="8">
              <XButton
                :title="t('login.btnQRCode')"
                class="w-[100%]"
                @click="setLoginState(LoginStateEnum.QR_CODE)"
              />
            </el-col>
            <el-col :span="8">
              <XButton
                :title="t('login.btnRegister')"
                class="w-[100%]"
                @click="setLoginState(LoginStateEnum.REGISTER)"
              />
            </el-col>
          </el-row>
        </el-form-item>
      </el-col>
      <el-divider content-position="center">{{ t('login.otherLogin') }}</el-divider>
      <el-col :span="24" style="padding-left: 10px; padding-right: 10px">
        <el-form-item>
          <div class="flex justify-between w-[100%]">
            <Icon
              v-for="(item, key) in socialList"
              :key="key"
              :icon="item.icon"
              :size="30"
              class="cursor-pointer anticon"
              color="#999"
              @click="doSocialLogin(item.type)"
            />
          </div>
        </el-form-item>
      </el-col>
      <el-divider content-position="center">萌新必读</el-divider>
      <el-col :span="24" style="padding-left: 10px; padding-right: 10px">
        <el-form-item>
          <div class="flex justify-between w-[100%]">
            <el-link href="https://doc.iocoder.cn/" target="_blank">📚开发指南</el-link>
            <el-link href="https://doc.iocoder.cn/video/" target="_blank">🔥视频教程</el-link>
            <el-link href="https://www.iocoder.cn/Interview/good-collection/" target="_blank">
              ⚡面试手册
            </el-link>
            <el-link href="http://static.yudao.iocoder.cn/mp/Aix9975.jpeg" target="_blank">
              🤝外包咨询
            </el-link>
          </div>
        </el-form-item>
      </el-col> -->
    </el-row>
  </el-form>
  <div
    v-if="isForget"
    class="w-30rem h-auto m-auto rounded-1xl bg-white shadow-login-win <sm:(w-18.75rem shadow-login-mobile)"
  >
    <p
      class="w-[100%] h-4rem text-login-black text-1.25rem font-500 m-0 leading-4rem px-42px <sm:(px-20px h-45px leading-45px text-15px)"
    >
      设置新密码
    </p>
    <el-divider class="!m-0" />
    <div class="w-[100%] px-42px pt-12px pb-44px <sm:(px-20px pt-6px pb-28px)">
      <p class="m-0 mt-20px text-login-black text-16px <sm:(mt-14px text-12px)">身份:</p>
      <el-radio-group v-model="forgetData.userType" class="mt-8px <sm:mt-4px">
        <el-radio :label="'student'">学生</el-radio>
        <el-radio :label="'staff'">教师</el-radio>
      </el-radio-group>
      <p class="m-0 mt-20px text-login-black text-16px <sm:(mt-14px text-12px)">学工号:</p>
      <el-input
        v-model.trim="forgetData.username"
        placeholder="请输入学工号"
        clearable
        class="inputNomal"
      />
      <p class="m-0 mt-20px text-login-black text-16px <sm:(mt-14px text-12px)">身份证号:</p>
      <el-input
        v-model.trim="forgetData.idCard"
        placeholder="请输入身份证号"
        clearable
        class="inputNomal"
      />
      <p class="m-0 mt-20px text-login-black text-16px <sm:(mt-14px text-12px)">新密码:</p>
      <el-input
        v-model.trim="forgetData.newPassword"
        type="password"
        show-password
        placeholder="请输入新密码"
        :minlength="4"
        class="inputNomal"
      />
      <p class="m-0 mt-20px text-login-black text-16px <sm:(mt-14px text-12px)">确认新密码:</p>
      <el-input
        v-model.trim="confirmPW"
        type="password"
        show-password
        placeholder="请输入新设置的密码"
        :minlength="4"
        :class="errorMessage ? 'inputError' : 'inputNomal'"
        @change="handleChange"
      />
      <div class="mt-12px flex items-center justify-start <sm:(mt-6px)" v-if="errorMessage">
        <el-icon color="#ED3F3F" :size="14">
          <WarnTriangleFilled />
        </el-icon>
        <span class="text-14px text-[#ED3F3F] ml-3px <sm:(text-12px ml-2px)">
          两次密码不一致，请检查
        </span>
      </div>
    </div>
    <el-divider class="!m-0" />
    <div class="w-[100%] h-72px flex items-center justify-end px-42px <sm:(h-56px px-20px)">
      <el-button
        class="w-100px !h-36px !bg-refuse-primary !text-t-primary !text-1rem hover:(!bg-refuse-hover !text-t-hover) focus:(!bg-refuse-focus !text-t-focus) <sm:(!w-64px !h-28px !text-13px)"
        @click="handleCencal"
      >
        取消
      </el-button>
      <el-button
        class="w-100px !h-36px !ml-8px !bg-agree-primary text-white hover:(!bg-agree-hover) focus:(!bg-agree-focus) <sm:(!w-64px !h-28px)"
        type="primary"
        @click="handleOk"
      >
        <span class="text-1rem <sm:(text-13px)">确认</span>
      </el-button>
    </div>
  </div>
</template>
<script lang="ts" name="LoginForm" setup>
import { ElLoading, ElNotification } from 'element-plus'
import LoginFormTitle from './LoginFormTitle.vue'
import type { RouteLocationNormalizedLoaded } from 'vue-router'

import { useIcon } from '@/hooks/web/useIcon'

import * as authUtil from '@/utils/auth'
import { usePermissionStore } from '@/store/modules/permission'
import * as LoginApi from '@/api/login'
// import { LoginStateEnum, useFormValid } from './useLogin'
import { LoginStateEnum, useFormValid, useLoginState } from './useLogin'

const { t } = useI18n()
// const message = useMessage()
// const iconHouse = useIcon({ icon: 'ep:house' })
const iconAvatar = useIcon({ icon: 'ep:avatar' })
const iconLock = useIcon({ icon: 'ep:lock' })
const formLogin = ref()
const { validForm } = useFormValid(formLogin)
// const { setLoginState, getLoginState } = useLoginState()
const { getLoginState } = useLoginState()
const { currentRoute, push } = useRouter()
const permissionStore = usePermissionStore()
const redirect = ref<string>('')
const loginLoading = ref(false)
const verify = ref()
// const captchaType = ref() // blockPuzzle 滑块 clickWord 点击文字
const captchaType = ref('blockPuzzle') // blockPuzzle 滑块 clickWord 点击文字
// const captchaType = ref('clickWord') // blockPuzzle 滑块 clickWord 点击文字

const getShow = computed(() => unref(getLoginState) === LoginStateEnum.LOGIN)

const dynamicImgSize = computed(() => {
  // 判断是否为移动端（< 640px）
  const isMobile = window.innerWidth < 640;
  return {
    width: isMobile ? `${window.innerWidth * 0.7}px` : `400px`,
    height: '200px'
  };
});

const LoginRules = {
  tenantName: [required],
  username: [required],
  password: [required]
}
const loginData = reactive({
  isShowPassword: false,
  captchaEnable: import.meta.env.VITE_APP_CAPTCHA_ENABLE,
  tenantEnable: import.meta.env.VITE_APP_TENANT_ENABLE,
  loginForm: {
    // tenantName: 'yrd',
    tenantName: '传媒学院',
    // username: 'admin',
    // password: 'admin123',
    username: '',
    password: '',
    captchaVerification: '',
    rememberMe: false
  }
})
// 是否进入忘记密码
const isForget = ref(false)
const forgetData = reactive({
  userType: '',
  username: '',
  idCard: '',
  newPassword: ''
})
const confirmPW = ref('')
const errorMessage = ref(false)

// const socialList = [
//   { icon: 'ant-design:github-filled', type: 0 },
//   { icon: 'ant-design:wechat-filled', type: 30 },
//   { icon: 'ant-design:alipay-circle-filled', type: 0 },
//   { icon: 'ant-design:dingtalk-circle-filled', type: 20 }
// ]

// 忘记密码
const toForgetForm = () => {
  isForget.value = true
}
const handleCencal = () => {
  isForget.value = false
  forgetData.userType = ''
  forgetData.username = ''
  forgetData.idCard = ''
  forgetData.newPassword = ''
  confirmPW.value = ''
  errorMessage.value = false
}
const handleOk = async () => {
  if (
    forgetData.username == '' ||
    forgetData.idCard == '' ||
    forgetData.newPassword == '' ||
    forgetData.userType == '' ||
    confirmPW.value == ''
  ) {
    alert('请填写完整信息')
    return
  }
  const res = await LoginApi.forgetPassword(forgetData)
  console.log('312', res)
  if (res) {
    ElNotification({
      title: '成功',
      message: '修改成功',
      type: 'success'
    })
    handleCencal()
  } else {
    ElNotification({
      title: '失败',
      message: '修改失败',
      type: 'error'
    })
  }
}

const handleChange = (val) => {
  console.log(val)
  if (val != forgetData.newPassword) {
    errorMessage.value = true
  } else {
    errorMessage.value = false
  }
}

// 获取验证码
const getCode = async () => {
  // 安卓/苹果、电脑端  区分
  //   function isAndroidDevice() {
  //     var userAgent = navigator.userAgent.toLowerCase()
  //     return userAgent.indexOf('android') > -1
  //   }
  //   // const captchaType = ref('blockPuzzle') // blockPuzzle 滑块 clickWord 点击文字
  //   // const captchaType = ref('clickWord') // blockPuzzle 滑块 clickWord 点击文字
  //   if (isAndroidDevice()) {
  //     console.log('This is an Android device.')
  //     captchaType.value = 'clickWord'
  //   } else {
  //     console.log('This is not an Android device.')
  //     captchaType.value = 'blockPuzzle'
  //   }
  // 情况一，未开启：则直接登录
  if (loginData.captchaEnable === 'false') {
    await handleLogin({})
  } else {
    // 情况二，已开启：则展示验证码；只有完成验证码的情况，才进行登录

    // 弹出验证码
    verify.value.show()
  }
}
//获取租户ID
const getTenantId = async () => {
  if (loginData.tenantEnable === 'true') {
    const res = await LoginApi.getTenantIdByName(loginData.loginForm.tenantName)
    authUtil.setTenantId(res)
  }
}
// 记住我
const getCookie = () => {
  const loginForm = authUtil.getLoginForm()
  if (loginForm) {
    loginData.loginForm = {
      ...loginData.loginForm,
      username: loginForm.username ? loginForm.username : loginData.loginForm.username,
      password: loginForm.password ? loginForm.password : loginData.loginForm.password,
      rememberMe: loginForm.rememberMe ? true : false,
      tenantName: loginForm.tenantName ? loginForm.tenantName : loginData.loginForm.tenantName
    }
  }
}
// 登录
const handleLogin = async (params) => {
  loginLoading.value = true
  try {
    await getTenantId()
    const data = await validForm()
    if (!data) {
      return
    }
    loginData.loginForm.captchaVerification = params.captchaVerification
    const res = await LoginApi.login(loginData.loginForm)
    if (!res) {
      return
    }
    ElLoading.service({
      lock: true,
      text: '正在加载系统中...',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    if (loginData.loginForm.rememberMe) {
      authUtil.setLoginForm(loginData.loginForm)
    } else {
      authUtil.removeLoginForm()
    }
    authUtil.setToken(res)
    if (!redirect.value) {
      redirect.value = '/'
    }
    // 判断是否为SSO登录
    console.log(redirect, window.location.href, permissionStore)
    if (redirect.value.indexOf('sso') !== -1) {
      window.location.href = window.location.href.replace('/login?redirect=', '')
    } else {
      push({ path: redirect.value || permissionStore.addRouters[0].path })
    }
  } catch (error) {
    loginLoading.value = false
  } finally {
    setTimeout(() => {
      const loadingInstance = ElLoading.service()
      loadingInstance.close()
    }, 400)
  }
}

// // 社交登录
// const doSocialLogin = async (type: number) => {
//   if (type === 0) {
//     message.error('此方式未配置')
//   } else {
//     loginLoading.value = true
//     if (loginData.tenantEnable === 'true') {
//       await message.prompt('请输入租户名称', t('common.reminder')).then(async ({ value }) => {
//         const res = await LoginApi.getTenantIdByName(value)
//         authUtil.setTenantId(res)
//       })
//     }
//     // 计算 redirectUri
//     const redirectUri =
//       location.origin + '/social-login?type=' + type + '&redirect=' + (redirect.value || '/')
//     // 进行跳转
//     const res = await LoginApi.socialAuthRedirect(type, encodeURIComponent(redirectUri))
//     window.location.href = res
//   }
// }
watch(
  () => currentRoute.value,
  (route: RouteLocationNormalizedLoaded) => {
    redirect.value = route?.query?.redirect as string
  },
  {
    immediate: true
  }
)
onMounted(() => {
  getCookie()
})
</script>

<style lang="scss" scoped>
:deep(.anticon) {
  &:hover {
    color: var(--el-color-primary) !important;
  }
}
:deep(.el-icon, .el-code span) {
  font-size: 14px !important;
}
:deep(.el-code > span) {
  font-size: 14px !important;
}
:deep(.el-icon svg) {
  width: 14px !important;
  height: 14px !important;
}

@media (max-width: 639.99px) {
  :deep(.el-icon, .el-code span) {
    font-size: 12px !important;
  }
  :deep(.el-code > span) {
    font-size: 12px !important;
  }
  :deep(.el-icon svg) {
    width: 12px !important;
    height: 12px !important;
  }
}
.login-code {
  width: 100%;
  height: 38px;
  float: right;

  img {
    cursor: pointer;
    width: 100%;
    max-width: 100px;
    height: auto;
    vertical-align: middle;
  }
}
:deep(.inputError) {
  //   --el-input-border-color: #ED3F3F;
  margin-top: 8px;
  height: 42px;
  --el-input-bg-color: rgba(237, 63, 63, 0.1);
  --el-input-focus-border-color: transparent;
  .el-input__wrapper {
    box-shadow: none;
    .el-input__inner {
      font-size: 14px !important;
      color: #000;
    }
  }
}
:deep(.inputNomal) {
  margin-top: 8px;
  height: 42px;
  --el-input-bg-color: #f2f4f8;
  --el-input-focus-border-color: transparent;
  .el-input__wrapper {
    box-shadow: none;
    .el-input__inner {
      font-size: 14px !important;
      color: #000;
    }
  }
}

:deep(.loginInput) {
  --el-input-bg-color: #f2f4f8;
  --el-input-focus-border-color: transparent;
  .el-input__wrapper {
    box-shadow: none;
    .el-input__inner {
      font-size: 14px !important;
      color: #000;
    }
  }
}
:deep(.el-radio) {
  height: auto;
  .el-radio__label {
    color: #000;
  }
}

@media (max-width: 639.99px) {
  :deep(.inputError) {
    margin-top: 4px;
    height: 32px;
    --el-input-bg-color: rgba(237, 63, 63, 0.1);
    --el-input-focus-border-color: transparent;
    .el-input__wrapper {
      box-shadow: none;
      .el-input__inner {
        font-size: 12px !important;
        color: #000;
      }
    }
  }
  :deep(.inputNomal) {
    margin-top: 4px;
    height: 32px;
    --el-input-bg-color: #f2f4f8;
    --el-input-focus-border-color: transparent;
    .el-input__wrapper {
      box-shadow: none;
      .el-input__inner {
        font-size: 12px !important;
        color: #000;
      }
    }
  }

  :deep(.loginInput) {
    --el-input-bg-color: #f2f4f8;
    --el-input-focus-border-color: transparent;
    .el-input__wrapper {
      box-shadow: none;
      .el-input__inner {
        font-size: 12px !important;
        color: #000;
      }
    }
  }
  :deep(.el-radio) {
    .el-radio__inner {
      width: 12px;
      height: 12px;
    }
    .el-radio__label {
      font-size: 12px;
    }
  }
}
</style>
